<template>
  <a-modal
    :visible="visible"
    :title="member && member.userId ? '编辑会员' : '新增会员'"
    @ok="handleSubmit"
    @cancel="$emit('update:visible', false)"
    @visible-change="handleVisibleChange"
  >
    <a-form :model="form" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
      <a-form-item field="trueName" label="姓名">
        <a-input v-model="form.trueName" placeholder="请输入姓名" />
      </a-form-item>
      <a-form-item field="mobile" label="手机号">
        <a-input v-model="form.mobile" placeholder="请输入手机号" />
      </a-form-item>
      <a-form-item field="email" label="邮箱">
        <a-input v-model="form.email" placeholder="请输入邮箱" />
      </a-form-item>
      <a-form-item field="sex" label="性别">
        <a-radio-group v-model="form.sex">
          <a-radio :value="true">男</a-radio>
          <a-radio :value="false">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item field="status" label="状态">
        <a-radio-group v-model="form.status">
          <a-radio :value="true">启用</a-radio>
          <a-radio :value="false">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { MemberDetail } from '@/api/member'

// 定义组件属性
const props = defineProps<{
  visible: boolean
  member: MemberDetail | null
}>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'submit', form: MemberDetail): void
}>()

// 处理对话框可见性变化
const handleVisibleChange = (val: boolean) => {
  emit('update:visible', val)
}

// 表单数据
const form = ref<MemberDetail>({
  userId: 0,
  trueName: '',
  mobile: '',
  sex: true,
  status: true,
  email: '',
})

// 监听member变化，更新表单数据
watch(
  () => props.member,
  (newVal) => {
    if (newVal) {
      form.value = { ...newVal }
    } else {
      // 重置表单为默认值
      form.value = {
        userId: 0,
        trueName: '',
        mobile: '',
        sex: true,
        status: true,
        email: '',
      }
    }
  },
  { immediate: true, deep: true }
)

// 提交表单
const handleSubmit = () => {
  emit('submit', form.value)
}
</script>

<style scoped lang="less">
// 组件特定样式可以在这里添加
</style>
